import * as path from "path";
import { BreezrPresetConfig } from "@alicloud/console-toolkit-preset-official";
import { getModifyPresetConfig } from "../../getModifyPresetConfig";

const outputPath = process.env.OUTPUT_PATH || "doc-dist";
const servePath = process.env.SERVE_PATH;
const consoleOSId = process.env.CONSOLEOS_ID;
const webpackConfigPath = process.env.WEBPACK_CONFIG_PATH;
const pkgRoot = path.resolve(__dirname, "../../../");
const presetOfficialConfigPath = process.env.PRESET_OFFICIAL_CONFIG_PATH;

if (!servePath) {
  throw new Error(`must provide process.env.SERVE_PATH to host`);
}
if (!consoleOSId) {
  throw new Error(`must provide process.env.CONSOLEOS_ID to host`);
}

export const config = ({
  port,
  isDev = true,
}: { port?: number; isDev?: boolean } = {}) => {
  const modifyConfig = getModifyPresetConfig(presetOfficialConfigPath, {
    type: "host",
    isDev,
  });

  const config: BreezrPresetConfig = {
    htmlFileName: path.resolve(pkgRoot, "src2/index.html"),
    typescript: {
      // @ts-ignore
      disableTypeChecker: true,
      useBabel: true,
    },
    port: port === undefined ? port : String(port),
    noOpen: true as any,
    // output: {
    //   path: path.join(outputPath, "host"),
    // } as any,
    webpack: (config: any) => {
      config.output.path = path.resolve(process.cwd(), outputPath, "host");
      config.output.publicPath = "/host/";
      if (isDev) {
        config.devServer.publicPath = "/host/";
        config.devServer.writeToDisk = true;
        // config.devServer.open = true;
        // config.devServer.openPage = "host/";
        config.devServer.historyApiFallback = {
          index: "/host/index.html",
        };
        config.devServer.liveReload = false;
        config.devServer.hot = false;
        config.devServer.inline = false;
      }
      config.entry.index = path.resolve(pkgRoot, "src2/HostApp/index.tsx");

      let result = config;
      if (webpackConfigPath) {
        const c = require(webpackConfigPath);
        result = c?.({ type: "host", isDev, config }) || result;
      }
      return result;
    },
    defineGlobalConstants: {
      __servePath: JSON.stringify(servePath),
      __consoleOSId: JSON.stringify(consoleOSId),
    },
    disableUpdator: true,
  };

  return {
    presets: [
      [
        require.resolve("@alicloud/console-toolkit-preset-official"),
        modifyConfig(config),
      ],
    ],
    plugins: [path.join(pkgRoot, "lib/config-webpack-plugin.js")],
  };
};
